﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Text.RegularExpressions;
using System.Data;
using System.Globalization;
using System.Data.OleDb;
using System.IO;


public class Common
{
    public static decimal stringToDecimal(string str)
    {
        decimal dec;
        if (decimal.TryParse(str, out dec))
        {
            return dec;
        }
        return 0;
    }

    public static string TrimLength(string str)
    {
        if (str.Length > 120)
        {
            return str.Substring(0, 120) + "...";
        }
        return str;
    }


    public static string ReadCookie(string key)
    {
        if (System.Web.HttpContext.Current.Request.Cookies[key] != null)
        {
            return System.Web.HttpContext.Current.Request.Cookies[key].Value;
        }
        return "";
    }
    public static void WriteCookie(string key, string value)
    {
        HttpCookie c = new HttpCookie(key, value);
        System.Web.HttpContext.Current.Response.Cookies.Add(c);
    }

    public static string ToShortDate(string date)
    {
        DateTime dt;
        CultureInfo culture = new CultureInfo("fr-FR");

        if (DateTime.TryParse(date, out dt))
            return dt.ToShortDateString();
        else if (DateTime.TryParse(date, culture, DateTimeStyles.None, out dt))
            return dt.ToShortDateString();
        else
            return "";
    }

    public static string ToDateTime(string date)
    {
        DateTime dt;
        CultureInfo culture = new CultureInfo("fr-FR");

        if (DateTime.TryParse(date, out dt))
            return dt.ToString("yyyy-MM-dd hh:mm:ss");
        else if (DateTime.TryParse(date, culture, DateTimeStyles.None, out dt))
            return dt.ToString("yyyy-MM-dd hh:mm:ss");
        else
            return "";
    }
    public static string ToShortTime(string date)
    {
        DateTime dt;
        if (DateTime.TryParse(date, out dt))
            return dt.ToShortTimeString();
        else return "";
    }
    public static float stringToFloat(string str)
    {
        float dec;
        if (float.TryParse(str, out dec))
        {
            return dec;
        }
        return 0;
    }
    public static bool isDecimal(string str)
    {
        decimal dec;
        if (decimal.TryParse(str, out dec))
        {
            return true;
        }
        return false;
    }

    public static bool isInt(string str)
    {
        int dec;
        if (int.TryParse(str, out dec))
        {
            return true;
        }
        return false;
    }

    public static string NoHTML(string Htmlstring) //去除HTML标记  
    {
        //删除脚本  
        Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //删除HTML  
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

        Htmlstring.Replace("<", "");
        Htmlstring.Replace(">", "");
        Htmlstring.Replace("\r\n", "");
        Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

        return Htmlstring;
    }
    public static string ConvertToUTF8(string s)
    {

        byte[] btCN = System.Text.Encoding.Default.GetBytes(s);
        string strUTF8 = System.Text.Encoding.UTF8.GetString(btCN);
        return strUTF8;
    }



    public static string ConvertToUTF8(string s, string code)
    {
        byte[] btCN = System.Text.Encoding.GetEncoding(code).GetBytes(s);
        string strUTF8 = System.Text.Encoding.UTF8.GetString(btCN);
        return strUTF8;
    }

    public static string ConvertToUTF8(string s, int code)
    {
        byte[] btCN = System.Text.Encoding.GetEncoding(code).GetBytes(s);
        string strUTF8 = System.Text.Encoding.UTF8.GetString(btCN);
        return strUTF8;
    }
    public static DataTable ReadFile(string path)
    {
        if (path != null && path.Length != 0)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(path, System.Text.Encoding.ASCII);
            int row = 0;
            DataTable dt = new DataTable();
            reader.Peek();
            while (reader.Peek() > 0)
            {
                string str = (reader.ReadLine());
                // /("[^"]+)，([^"]+")/g
                //System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("/(\"[^\"]*),([^\"]*\")/g");
                //str = reg.Replace(str,  "");

                string[] split;
                int splitLength;

                if (row == 0)
                    split = str.Split(',');
                else
                {
                    str = str.Replace("\",\"", "\b");
                    str = str.Replace("\"", "");
                    split = str.Split('\b');
                }
                splitLength = split.Length;
                if (splitLength < 20)
                {
                    split = str.Split(',');
                }

                //string[] split = str.Split(new char[] { ',' });
                if (row == 0)
                {
                    for (int i = 0; i < splitLength; i++)
                    {
                        DataColumn dc = new DataColumn(split[i]);
                        dt.Columns.Add(dc);
                    }
                    row++;
                }
                else
                {
                    System.Data.DataRow dr = dt.NewRow();
                    for (int i = 0; i < splitLength; i++)
                    {

                        if (splitLength > 43 && i == 16)
                        {
                            for (int idx = 0; idx < splitLength - 42; idx++)
                            {
                                dr[16] += split[i] + ",";
                                i++;
                            }
                        }
                        else
                        {
                            if (i == 3 || i == splitLength - 3 || i == splitLength - 4 || i == splitLength - 5 || i == splitLength - 6 || i == splitLength - 7)
                            {
                                dr[i] = Common.ConvertToUTF8(split[i], "gb2312");
                            }
                            else
                            {
                                dr[i] = split[i];
                            }
                        }
                    }
                    dt.Rows.Add(dr);
                }
            }

            return dt;

        }
        return null;
    }

    public static DataTable ReadCSV(string Filename)
    {
        string MyPath = System.IO.Path.GetDirectoryName(Filename);
        string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyPath + ";Extended Properties='text;HDR=Yes;FMT=Delimited'";
        string CmdText = "select * from [" + System.IO.Path.GetFileName(Filename) + "]";
        OleDbConnection Con = new OleDbConnection(ConnectionString);
        OleDbDataAdapter adptr = new OleDbDataAdapter(CmdText, Con);
        DataSet Ds = new DataSet();
        adptr.Fill(Ds);
        DataTable dt = Ds.Tables[0];

        return dt;
    }

    public static string ReadHtml(string Filename)
    {
        System.IO.File.Exists(Filename);
        string str=string.Empty;
        StreamReader reader = new StreamReader(Filename);
      
        while (reader.Peek() > 0)
        {
            str = reader.ReadToEnd();
        }
        reader.Close();

        return str;
    }
}
